package com.cat.bitOperation;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/minimum-array-end/
 * @create 2025/11/1 18:37
 * @since JDK17
 */

public class Solution16 {
    public long minEnd(int n, int x) {
        int high = 0;
        for (high = 31; high >= 0; high--) {    // 找到最高位
            if ((x >> high & 1) == 1) {
                break;
            }
        }
        int y = (high << 1) - 1 - x;    // 低位可以榨出多少油水
        if (y < n - 1) {    // 低位即可
            return x | y;
        } else if (y == n - 1) {
            return y;
        } else {
            long ans = n - 1 - y;
            ans = (ans << high + 1) | y;
            return ans;
        }
    }
}
